import React from 'react';
import './index.css';
import { Form, Input, Checkbox, Button, Icon, Alert } from 'antd';
import { connect } from 'dva';
@connect(state => ({}), {
  login: data => ({ type: 'user/login', payload: data }),
})
export default class Login extends React.Component {
  state = {
    login: { username: null, password: null },
    tip: false,
    msg: '用户名密码错误',
  };
  onFinish() {
    this.setState(
      {
        tip: Object.values(this.state.login).some(v => v == null),
      },
      () => {
        if (!this.state.tip) {
          try {
            this.props.login(this.state.login);
          } catch (error) {
            this.setState({
              tip: true,
            });
          }
        }
      },
    );
  }
  changeInput(e, prop) {
    const data = this.state.login;
    data[prop] = e.target.value;
    this.setState({
      login: data,
      tip: false,
    });
  }
  render() {
    return (
      <div className="login">
        <Alert
          type="error"
          message={this.state.msg}
          banner
          style={{
            display: this.state.tip ? 'block' : 'none',
          }}
        />
        <Form name="normal_login" className="login-form" ref="loginForm">
          <Form.Item
            rules={[{ required: true, message: 'Please input your Username!' }]}
          >
            <Input
              onChange={e => this.changeInput(e, 'username')}
              value={this.state.login.username}
              prefix={<Icon type="user" className="site-form-item-icon" />}
              placeholder="Username"
            />
          </Form.Item>
          <Form.Item
            rules={[{ required: true, message: 'Please input your Password!' }]}
          >
            <Input
              onChange={e => this.changeInput(e, 'password')}
              value={this.state.login.password}
              name="password"
              prefix={<Icon type="lock" className="site-form-item-icon" />}
              type="password"
              placeholder="Password"
            />
          </Form.Item>
          <Form.Item className="check-a">
            <Form.Item name="remember">
              <Checkbox>记住密码</Checkbox>
            </Form.Item>

            <a className="login-form-forgot" href="">
              忘记密码？
            </a>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className="login-form-button"
              onClick={() => this.onFinish()}
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
